package com.zq.zqmanager.socket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @program: zqmanager
 * @Date: 2020/3/8 13:06
 * @Author: zhengqiang
 * @Description:
 */
@ServerEndpoint(value = "/websocket/{nickname}")
@Component
public class MyWebSocket {

    private static CopyOnWriteArraySet<MyWebSocket> webSockets = new CopyOnWriteArraySet<MyWebSocket>();
    private Session session;

    @OnOpen
    public void onOpen(Session session, @PathParam("nickname") String nickname){
        this.session = session;
        webSockets.add(this);
        this.session.getAsyncRemote().sendText(nickname+"恭喜登录，当前在线人数"+webSockets.size());
    }

    @OnClose
    public void onClose(Session session){
        webSockets.remove(this);
    }

    @OnMessage
    public void onMessage(Session session,String message,@PathParam("nickname") String nickname){
        broadcast(nickname+":"+message);
    }

    private void broadcast(String message){
        for (MyWebSocket set : webSockets) {
            set.session.getAsyncRemote().sendText(message);
        }
    }

}
